﻿#region Header

/***************************************************************************
Author : Krishan Kaliraman (www.sharedwith.me)  Date: 1 Aug 2012
***************************************************************************/

#endregion Header

using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Data;
using System.Text;


namespace Common
{
    public class Activity
    {
        #region Properties

        public WorkItem WorkItem;
        public List<string> IdOfAlllinkedWorkItems = new List<string>();
        public List<Activity> LinkedChildWorkItems= new List<Activity>();
        public List<ActivityAttachment> Attachments = new List<ActivityAttachment>();
        public string AreaId { get; set; }
        public string AreaPath { get; set; }
        public string AssignedTo { get; set; }
        public string AttachedFileCount { get; set; }
        public string AuthorizedAs { get; set; }
        public string ActivityType { get; set; }
        public string AcceptanceCriteria { get; set; }
        
        public string ChangedBy { get; set; }
        public string ChangedDate { get; set; }
        public string CreatedBy { get; set; }
        public string CreatedDate { get; set; }
        public string Description { get; set; }
        public string DescriptionHtml { get; set; }        

        public string ExternalLinkCount { get; set; }
        public string History { get; set; }
        public string HyperLinkCount { get; set; }
        public string Id { get; set; }
        public string IterationId { get; set; }

        public string IterationPath { get; set; }
        public string NodeName { get; set; }
        public string ParentId { get; set; }
        public string Reason { get; set; }
        public string RelatedLinkCount { get; set; }
        public double RemainingWork { get; set; }
        public string Rev { get; set; }

        public string RevisedDate { get; set; }
        public string State { get; set; }
        public string TeamProject { get; set; }
        public string Title { get; set; }
        public double TotalWork { get; set; }
        public double WorkDone { get; set; }
        public string WorkItemType { get; set; }

        public List<DiscussionItem> DiscussionHistory { get; set; }

        #endregion

        # region Constructor

        public Activity()
        { 

        }

        public Activity(WorkItem workItem)
        {
            this.WorkItem = workItem;
            FillAllProperties();
            FillLinksOfWorkItem();
        }
        public Activity(WorkItem workItem, string taskActivityType)
        {
            this.WorkItem = workItem;
            FillAllProperties();
            FillTaskProperties(taskActivityType);
        }

        private void FillTaskProperties(string taskActivityType)
        {
            //if ((State == "In Progress") || (State =="To Do"))
            //{
                object remainingWork = WorkItem[WorkItem.Fields["Microsoft.VSTS.Scheduling.RemainingWork"].Name];
                if (remainingWork != null)
                {
                    RemainingWork = Convert.ToDouble(remainingWork);
                }
            //}
            if((State =="In Progress")||State=="Done")
            {
                List<double> revisionValues = new List<double>();
                foreach (Revision revision in WorkItem.Revisions )
                {
                    Console.WriteLine("Revision : {0}", revision.Index.ToString());
                    object remainingWorkInRevision = revision.Fields["Remaining Work"].OriginalValue;
                    if (remainingWorkInRevision != null)
                    {
                        string effortRemaining = remainingWorkInRevision.ToString();
                        revisionValues.Add(Convert.ToDouble(effortRemaining));
                    }
                }
                if(revisionValues .Count>0)
                {
                    TotalWork = revisionValues.Max();
                    WorkDone = TotalWork - RemainingWork;
                }
            }
            ActivityType = taskActivityType;
        }

        private void FillLinksOfWorkItem()
        {
            foreach (WorkItemLink currentLinkedItem in WorkItem.WorkItemLinks)
            {
                IdOfAlllinkedWorkItems.Add(currentLinkedItem.TargetId.ToString());
            }
        }

        # endregion

        # region PrivateMethods

        private void FillAllProperties()
        {
            AreaId = WorkItem[WorkItem.Fields["System.AreaId"].Name].ToString();
            AreaPath = WorkItem[WorkItem.Fields["System.AreaPath"].Name].ToString();
            AssignedTo = WorkItem[WorkItem.Fields["System.AssignedTo"].Name].ToString();
            AttachedFileCount = WorkItem[WorkItem.Fields["System.AttachedFileCount"].Name].ToString();
            AuthorizedAs = WorkItem[WorkItem.Fields["System.AuthorizedAs"].Name].ToString();

            ChangedBy = WorkItem[WorkItem.Fields["System.ChangedBy"].Name].ToString();
            ChangedDate = WorkItem[WorkItem.Fields["System.ChangedDate"].Name].ToString();
            CreatedBy = WorkItem[WorkItem.Fields["System.CreatedBy"].Name].ToString();
            CreatedDate = WorkItem[WorkItem.Fields["System.CreatedDate"].Name].ToString();
            Description = WorkItem[WorkItem.Fields["System.Description"].Name].ToString();

            ExternalLinkCount = WorkItem[WorkItem.Fields["System.ExternalLinkCount"].Name].ToString();
            History = WorkItem[WorkItem.Fields["System.History"].Name].ToString();
            HyperLinkCount = WorkItem[WorkItem.Fields["System.HyperLinkCount"].Name].ToString();
            Id = WorkItem[WorkItem.Fields["System.Id"].Name].ToString();
            IterationId = WorkItem[WorkItem.Fields["System.IterationId"].Name].ToString();

            IterationPath = WorkItem[WorkItem.Fields["System.IterationPath"].Name].ToString();
            NodeName = WorkItem[WorkItem.Fields["System.NodeName"].Name].ToString();
            Reason = WorkItem[WorkItem.Fields["System.Reason"].Name].ToString();
            RelatedLinkCount = WorkItem[WorkItem.Fields["System.RelatedLinkCount"].Name].ToString();
            Rev = WorkItem[WorkItem.Fields["System.Rev"].Name].ToString();

            RevisedDate = WorkItem[WorkItem.Fields["System.RevisedDate"].Name].ToString();
            State = WorkItem[WorkItem.Fields["System.State"].Name].ToString();
            TeamProject = WorkItem[WorkItem.Fields["System.TeamProject"].Name].ToString();
            Title = WorkItem[WorkItem.Fields["System.Title"].Name].ToString();
            FillActivityType();
        }

        private void FillActivityType()
        {
            string workItemType = WorkItem[WorkItem.Fields["System.WorkItemType"].Name].ToString();
            if (workItemType.ToUpper() == "PRODUCT BACKLOG ITEM")
            {
                WorkItemType = "PBI";
            }
            else
            {
                WorkItemType = workItemType;
            }
            if (workItemType.ToUpper() == "TASK")
            {
                ActivityType = WorkItem[WorkItem.Fields["Activity"].Name].ToString();
            }
        }

        # endregion

        public void FillDiscussionHistoryOfActivity()
        {
            DiscussionHistory = FetchDiscussionHistoryForTheActivity(Id);            
        }

        private List<DiscussionItem> FetchDiscussionHistoryForTheActivity(string activityId)
        {
            DataTable activityDiscussionsdataTable = Helper.GetDataTable("SELECT *  FROM ActivityDiscussions where ActivityId=" + activityId + " order by EntryDate asc ");
            DataTable activityAttachmentdataTable = Helper.GetDataTable("SELECT *  FROM ActivityAttachments where ActivityId=" + activityId);
            List<DiscussionItem> discussionItems = new List<DiscussionItem>();
             foreach (DataRow  row in activityDiscussionsdataTable .Rows)
             {
                 DiscussionItem discussionItem = new DiscussionItem();
                 discussionItem.DiscussionEntryId = row["DiscussionEntryId"].ToString();
                 discussionItem.DiscussionText = row["DiscussionText"].ToString();
                 discussionItem.EnteredFor = row["EnteredFor"].ToString();
                 discussionItem.DiscussionType = row["DiscussionType"].ToString();
                 discussionItem.EnteredBySmallName = FetchFirstName( row["EnteredBy"].ToString());
                 discussionItem.EnteredByFullName = row["EnteredBy"].ToString();
                 discussionItem.EmailTo = row["EmailTo"].ToString();
                 discussionItem.EmailCC = row["EmailCC"].ToString();
                 discussionItem.ParentDiscussionEntryId = row["ParentDiscussionEntryId"].ToString();
                 discussionItem.EntryDate = Convert.ToDateTime(row["EntryDate"].ToString());
                 if(activityAttachmentdataTable.Rows.Count>0)
                 {
                     discussionItem.DocumentsAttached=new List<ActivityAttachment>();
                     foreach (DataRow currentRow in activityAttachmentdataTable.Rows)
                     {
                         if (currentRow["DiscussionActivityId"].ToString() == discussionItem.DiscussionEntryId)
                         {
                             ActivityAttachment newAttachment = new ActivityAttachment();
                             newAttachment.Name = currentRow["AttachmentName"].ToString();
                             discussionItem.DocumentsAttached.Add(newAttachment);
                         }
                     }
                 }
                 discussionItems.Add(discussionItem);
	         }
             return discussionItems;
        }

        private string FetchFirstName(string fullName)
        {
            string[] fullNameArray = fullName.Split(' ');
            return fullNameArray[0];
        }

        public void EnterDiscussionHistoryForTheActivity(DiscussionItem discussionItem)
        {
            StringBuilder queryBuilder = new StringBuilder();
            queryBuilder.Append("insert into ActivityDiscussions(ActivityId,DiscussionText,DiscussionType,EnteredBy, EnteredFor, EntryDate )  values(");
            queryBuilder.Append(discussionItem.DiscussionActivityId + ",'");
            queryBuilder.Append(discussionItem.DiscussionText + "','");
            queryBuilder.Append(discussionItem.DiscussionType + "','");
            queryBuilder.Append(discussionItem.EnteredBySmallName + "','");
            queryBuilder.Append(discussionItem.EnteredFor + "','");
            queryBuilder.Append(discussionItem.EntryDate + "')");
            Helper.ExecuteSqlStatement(queryBuilder.ToString());
        }


        public void FillDiscussionPageRequiredProperties()
        {

            try
            {
                DescriptionHtml = WorkItem[WorkItem.Fields["Microsoft.VSTS.Common.DescriptionHtml"].Name].ToString();
            }
            catch (Exception ex)
            {
                DescriptionHtml = string.Empty;
            }
            try
            {
                AcceptanceCriteria = WorkItem[WorkItem.Fields["Microsoft.VSTS.Common.AcceptanceCriteria"].Name].ToString();
            }
            catch (Exception ex)
            {
                AcceptanceCriteria = string.Empty;
            }
            AttachmentCollection attachmentCollection = WorkItem.Attachments;
            foreach (Attachment attachment in attachmentCollection)
            {
                Attachments.Add(new ActivityAttachment() { Name = attachment.Name, Url = attachment .Uri.AbsoluteUri});
            }
            FillActivityType();
        }

        public void UploadAttachment(string filePath,string comment)
        {
            Attachment attachment = new Attachment(filePath, comment);            
            WorkItem.Attachments.Add(attachment);
            WorkItem.Save();            
        }

        internal void UploadAttachmentAndEnterDiscussionItem(string filePath, string fileName, DiscussionItem discussionItem, out string discussionEntryId)
        {
            StringBuilder discusionItemQueryBuilder = new StringBuilder();
            if(string.IsNullOrEmpty(discussionItem.ParentDiscussionEntryId))
            {
                discusionItemQueryBuilder.Append("insert into ActivityDiscussions(ActivityId,DiscussionText,DiscussionType,EnteredBy, EnteredFor,EmailTo, EmailCC, EntryDate )  values(");
            }
            else
            {
                discusionItemQueryBuilder.Append("insert into ActivityDiscussions(ActivityId,DiscussionText,DiscussionType,EnteredBy, EnteredFor,EmailTo, EmailCC,ParentDiscussionEntryId, EntryDate )  values(");
            }
            discusionItemQueryBuilder.Append(discussionItem.DiscussionActivityId + ",'");
            discusionItemQueryBuilder.Append(discussionItem.DiscussionText + "','");
            discusionItemQueryBuilder.Append(discussionItem.DiscussionType + "','");
            discusionItemQueryBuilder.Append(discussionItem.EnteredBySmallName + "','");
            discusionItemQueryBuilder.Append(discussionItem.EnteredFor + "','");
            discusionItemQueryBuilder.Append(discussionItem.EmailTo + "','");
            discusionItemQueryBuilder.Append(discussionItem.EmailCC + "',");
            if (!string.IsNullOrEmpty(discussionItem.ParentDiscussionEntryId))
            {
                discusionItemQueryBuilder.Append(discussionItem.ParentDiscussionEntryId + ",'");
            }
            else
            {
                discusionItemQueryBuilder.Append("'");
            }
            discusionItemQueryBuilder.Append(discussionItem.EntryDate + "')");
            Helper.ExecuteSqlStatement(discusionItemQueryBuilder.ToString());
            if (!string.IsNullOrEmpty(filePath))
            {
                UploadAttachment(filePath, fileName);
            }

            string selectQyueryForEnteredDiscussionItem = "select DiscussionEntryId from ActivityDiscussions where EntryDate='" + discussionItem.EntryDate + "'";
            DataTable dataTable = Helper.GetDataTable(selectQyueryForEnteredDiscussionItem);
            string discussionId = string.Empty;
            if (dataTable.Rows.Count > 0 )
            {
                discussionId= dataTable.Rows[0]["DiscussionEntryId"].ToString();
                if(!string.IsNullOrEmpty(fileName))
                {
                    StringBuilder discussionAttachmentQueryBuilder = new StringBuilder();
                    discussionAttachmentQueryBuilder.Append(
                        "insert into ActivityAttachments(ActivityId,DiscussionActivityId,AttachmentName) values(");
                    discussionAttachmentQueryBuilder.Append(discussionItem.DiscussionActivityId + ",");
                    discussionAttachmentQueryBuilder.Append(discussionId + ",'");
                    discussionAttachmentQueryBuilder.Append(fileName + "')");
                    Helper.ExecuteSqlStatement(discussionAttachmentQueryBuilder.ToString());
                }
            }
            discussionEntryId = discussionId;
        }
    }    
}
